package com.xs.project.service.impl;

import com.xs.project.service.FileService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class FileServiceImpl implements FileService {

    private static final String BASE_DIR = "E:\\local-db\\";
    @Override
    public String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return "File is empty";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(BASE_DIR + file.getOriginalFilename());
            Files.write(path, bytes);
            return BASE_DIR+file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return "Could not upload the file: " + e.getMessage();
        }
    }

    @Override
    public void downloadFile(String fileName, String filePathStr, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
            File file=new File(filePathStr);
            if(!file.exists()){
                throw new Exception("文件不存在");
            }
            response.setHeader("Content-disposition","attachment;filename="+ fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream,response.getOutputStream());
            response.flushBuffer();
            fileInputStream.close();
        }catch (Exception e){

        }

    }
}
